"use client";

import React from "react";
import dynamic from "next/dynamic";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import remarkBreaks from "remark-breaks";
import remarkToc from "remark-toc";
import rehypeRaw from "rehype-raw";
import rehypeKatex from "rehype-katex";
import rehypeHighlight from "rehype-highlight";
import { Card } from "@/components/ui/card";
import "katex/dist/katex.min.css";
import "highlight.js/styles/github.css";

// Mermaid 动态组件（避免 SSR 报错）
const Mermaid = dynamic(() => import("@/components/tools/MermaidRender"), {
  ssr: false,
});

function normalizeMarkdown(rawText: string): string {
  return rawText
    .replace(/\r\n/g, "\n")
    .replace(/\t/g, "    ")
    .replace(/\\n/g, "\n")
    .trim();
}

export default function MarkdownView({ markdown }: { markdown: string }) {
  const cleanedMarkdown = normalizeMarkdown(markdown);

  return (
    <Card className="prose prose-custom prose-slate max-w-[2000px] p-6 border-none">
      <ReactMarkdown
        remarkPlugins={[remarkGfm, remarkMath, remarkBreaks, remarkToc]}
        rehypePlugins={[rehypeRaw, rehypeKatex, rehypeHighlight]}
        components={{
          code({ className, children, ...props }) {
            const value = String(children).trim();
            if (className?.includes("language-mermaid")) {
              return <Mermaid chart={value} />;
            }

            return (
              <pre className="p-4 bg-gray-100 dark:bg-gray-800 rounded-lg overflow-x-auto text-sm">
                <code className={className} {...props}>
                  {children}
                </code>
              </pre>
            );
          },
          table({ children }) {
            return (
              <div className="overflow-x-auto">
                <table className="table-auto border-collapse">{children}</table>
              </div>
            );
          },
          blockquote({ children }) {
            return (
              <blockquote className="border-l-4 border-blue-500 pl-4 italic text-muted-foreground">
                {children}
              </blockquote>
            );
          },
          img({ src = "", alt }) {
            return (
              <img
                src={src}
                alt={alt}
                className="rounded-lg shadow max-w-full h-auto object-contain my-2"
              />
            );
          },
        }}
      >
        {cleanedMarkdown}
      </ReactMarkdown>
    </Card>
  );
}
